//
//  MovieListViewController.m
//  UI-21-豆豆豆瓣
//
//  Created by dllo on 15/11/6.
//  Copyright © 2015年 Wang Hao. All rights reserved.
//

#import "MovieListViewController.h"
#import "ListTableViewCell.h"
#import "MovieDetailViewController.h"
#import "Movie.h"
#import "AppTools.h"
#import "DatabaseSingleton.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "Reachability.h"

@interface MovieListViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,ListTableViewCellDelegate>

@property (nonatomic, retain) UITableView *myTableView;

@property (nonatomic, retain) NSMutableArray *movieArray1;

@property (nonatomic, assign) BOOL isUpload;
@property (nonatomic, retain) MBProgressHUD *hup;

@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, retain) NSMutableArray *seachArray;
@end

@implementation MovieListViewController

- (void)dealloc
{
    [_movieArray1 release];
    [_myTableView release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 375, 667-68) style:UITableViewStylePlain];
    [self.view addSubview:self.myTableView];
    
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    
    [_myTableView release];
    
    [self.myTableView registerClass:[ListTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.movieArray1 = [NSMutableArray array];
    
    
    [[DatabaseSingleton shareDatabaseSingleton] openDB];
    NSMutableArray *array = [[DatabaseSingleton shareDatabaseSingleton] selectData];
    self.movieArray1 = [NSMutableArray arrayWithArray:array];
    
    
    self.seachArray = [NSMutableArray array];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 375, 30)];
    self.isEdit = NO;
    self.searchBar.showsCancelButton = NO;
    self.searchBar.delegate = self;
    
    UIView *first = [self.searchBar.subviews objectAtIndex:0];
    first = [first.subviews objectAtIndex:0];
    [first removeFromSuperview];
    self.searchBar.barStyle = UIBarStyleBlack;
    self.myTableView.tableHeaderView = self.searchBar;
    [self.searchBar release];
//    [self getWorking];
    //6.关闭数据库
    //[self.db close];
    
    [self addHeaderRefresh];
    [self addFooterRefresh];
    self.isUpload = NO;
}

-(void)addHeaderRefresh{
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"没有网络连接");
            // 没有网络连接
            
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            NSLog(@"使用3G网络");
            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            NSLog(@"使用WiFi网络");
            [self.myTableView addHeaderWithCallback:^{
                //加个菊花
                self.isUpload = NO;
                [self getWorking];
                self.hup = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [self.hup show:YES];
                self.hup.labelText = @"loading.....";
                //[self.view bringSubviewToFront:self.hup];
                
                NSLog(@"下拉");
            }];
             [self.myTableView headerBeginRefreshing];

            break;
    }
   
    
    }

-(void)addFooterRefresh{
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"没有网络连接");
            // 没有网络连接
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            NSLog(@"使用3G网络");
            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            NSLog(@"使用WiFi网络");
            [self.myTableView addFooterWithCallback:^{
                
                [self getWorking];
                
                
                NSLog(@"上拉");
                
            }];
            break;
    }
    
}






-(void)getWorking{
    [AppTools getUrl:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php" block:^(id result) {
        
        if(self.isUpload  == NO){
            [self.movieArray1 removeAllObjects];
            [[DatabaseSingleton shareDatabaseSingleton] dropTable];
            
        }

        NSMutableDictionary *dic = result;
        NSString *reason = [dic objectForKey:@"reason"];
        NSMutableArray *array = [dic objectForKey:@"result"];
        if ([reason isEqualToString:@"success"]) {
            
            for (NSMutableDictionary *dic in array) {
                Movie *movie = [[Movie alloc] init];
                [movie setValuesForKeysWithDictionary:dic];
                [self.movieArray1 addObject:movie];
                //插入数据
               [[DatabaseSingleton shareDatabaseSingleton] insertData:movie];
                
                [movie release];
            }
            [self.myTableView reloadData];
            [self.myTableView headerEndRefreshing];
            [self.myTableView footerEndRefreshing];
            [self.myTableView reloadData];
            //取消菊花
            [self.hup hide:YES];
        }else{
            
            NSLog(@"请求失败");
        }
        
        
    }];

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.isEdit) {
        
        return self.seachArray.count;
        
    }else
    {
        return self.movieArray1.count;
        
    }

    

    //return self.movieArray1.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIndent = @"cell";
    ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndent];
    
    Movie *movie = [[Movie alloc] init];
    // MovieList *movie = [self.movieArray objectAtIndex:indexPath.row];
    if (self.isEdit) {
        movie = [self.seachArray objectAtIndex:indexPath.row];
        
    }else{
        
        movie = [self.movieArray1 objectAtIndex:indexPath.row];
        
    }
    
    cell.movie = movie;
    cell.movie.indexPath = indexPath;
    cell.listDelegate = self;
    //cell.movie = [self.movieArray1 objectAtIndex:indexPath.row];
    return cell;
    
    
}
-(void)sentModel:(Movie *)mov{
    
    NSLog(@"  movieName ===  %@,  indexPath.row === %ld  indexPath.section == %ld",mov.movieName, mov.indexPath.row, mov.indexPath.section);
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 160;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MovieDetailViewController *movDetail = [[MovieDetailViewController alloc] init];
    Movie *mov = [self.movieArray1 objectAtIndex:indexPath.row];
    movDetail.movie = mov;
    [self.navigationController pushViewController:movDetail animated:YES];
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    NSLog(@"允许编辑");
    return YES;
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = nil;
    self.isEdit = NO;
    [self.myTableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText isEqualToString:@""]) {
        self.isEdit = NO;
        [self.myTableView reloadData];
        return;
    }
    self.isEdit = YES;
    [self.seachArray removeAllObjects];
    for (Movie *movie in self.movieArray1) {
        
        if ([movie.movieName containsString:searchText]) {
            
            [self.seachArray addObject:movie];
            
            [self.myTableView reloadData];
            
        }
        
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
